﻿#include "UserManager.h"
#include <iostream>

bool UserManager::registerUser(const std::string &username,
                               const std::string &password, int age,
                               const std::string &email) {
    return db.insertUser(username, password, age, email);
}

bool UserManager::loginUser(const std::string &username,
                            const std::string &password, SOCKET sock,
                            int &userId) {
    if (!db.checkUser(username, password, userId)) {
        return false;
    }

    std::lock_guard<std::mutex> lock(mtx);
    if (onlineUsers.find(username) != onlineUsers.end()) {
        return false; // 已在线
    }

    onlineUsers[username] = {username, sock, userId};
    return true;
}

void UserManager::logoutUser(const std::string &username) {
    std::lock_guard<std::mutex> lock(mtx);
    onlineUsers.erase(username);
}

bool UserManager::isOnline(const std::string &username) {
    std::lock_guard<std::mutex> lock(mtx);
    return onlineUsers.find(username) != onlineUsers.end();
}

SOCKET UserManager::getSocket(const std::string &username) {
    std::lock_guard<std::mutex> lock(mtx);
    auto it = onlineUsers.find(username);
    return it != onlineUsers.end() ? it->second.socket : INVALID_SOCKET;
}

std::vector<std::string> UserManager::getOnlineUsernames() {
    std::lock_guard<std::mutex> lock(mtx);
    std::vector<std::string> names;
    for (const auto &pair : onlineUsers) {
        names.push_back(pair.first);
    }
    return names;
}